<?php
declare (strict_types=1);

namespace app;

use app\model\Settings;
use app\model\UserToken;
use think\App;
use think\exception\ValidateException;
use think\Validate;
use think\View;

/**
 * 控制器基础类
 */
abstract class BaseController extends View
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];
    protected $user = false;

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        // 控制器初始化
        $this->initialize();
        $this->assign('getConfig', function ($key, $def = '##') {
            return Settings::Config($key, $def);
        });
    }

    protected function getUser($isExit = false)
    {
        if ($this->user) {
            return $this->user;
        }
        $cookie = $this->request->cookie('UserToken');
        $id = $this->request->cookie('UserId');
        $result = UserToken::withjoin('user')->where("token", $cookie)->find();
        if ($result) {
            if ($result['user']['uid'] != $id) {
                if ($isExit) {
                    over();
                }
            }
            if ($result['user']['status'] == '2') {
                if ($isExit) {
                    over();
                }
            }
            $day7 = time() - (60 * 60 * 24 * 7);
            if ($day7 > $result['time']) { //如果当前时间-往前推7天大于上次登录时间则toekn过期
                UserToken::where('time', '<', $day7)->delete();
                if ($isExit) {
                    over();
                }
            }
            $this->user = $result['user'];
            return $result['user'];
        }
        if ($isExit) {
            over();
        }
    }

    protected function LoginInfo()
    {
        $id = $this->request->cookie('UserId');
        $cookie = $this->request->cookie('UserToken');
        if ($cookie && $id) {
            $this->getUser();
        }
        $this->assign('isLogin', $this->user);
        $this->assign('user', $this->user);
        return $cookie;
    }

    // 初始化
    protected function initialize()
    {
        $this->LoginInfo();
        $this->assign("title", Settings::Config("title", ""));
        $this->assign("site", Settings::Config("app_name", ""));
        $this->assign('keywords', Settings::Config('keywords', ''));
        $this->assign('description', Settings::Config('description', ''));
        $this->assign("version", env("version", date('YmdHi')));
    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    public function success($msg, $data = []): \think\response\Json
    {
        if (is_array($msg)) {
            return json(['msg' => "", "code" => 1, "data" => $msg]);
        }
        return json(['msg' => $msg, "code" => 1, "data" => $data]);
    }

    public function error($msg, $data = []): \think\response\Json
    {
        if (is_array($msg)) {
            return json(['msg' => "", "code" => 0, "data" => $msg]);
        }
        return json(['msg' => $msg, "code" => 0, "data" => $data]);
    }
}
